<?php

namespace app\index\controller;

use think\Controller;
use think\view;
use think\Db;
use think\Input;



class My extends Controller
{

  //前台代码
  public function index()
  {
    return $this->fetch();
  }



  public function index1()
  {
    return $this->fetch();
  }


  //LIST
  public function lists()
  {
    $data = Db::table('goods')->order('name asc')->select();
    return json($data);
  }


  //add
  public function add()
  {
    return $this->fetch();
  }


  //added
  public function added()
  {
    $data = input('post.');
    $res = Db::table('goods')->insert($data);

    if ($res) {
      return  '添加成功';
    } else {
      return  "添加失败";
    }
  }


  //del
  public function del()
  {
    $id = input('get.id');
    $res = Db::table('goods')->where("id", $id)->delete();
    if ($res) {
      return  '删除成功';
    } else {
      return  "删除失败";
    }
  }


  //batchdel
  public function batchdel()
  {
    $ids = input('post.ids');
    $res = Db::table('goods')->delete($ids);
    if ($res) {
      return  '删除成功';
    } else {
      return  "删除失败";
    }
  }


  //修改
  public function edit()
  {
    return $this->fetch();
  }

  //ajax保存修改
  public function editSave()
  {
    $data = input('post.');
    $id = input('post.id');

    $result = Db::table('goods')->where('id', $id)->update($data);
    if ($result) {
      return '修改成功';
    } else {
      return '修改失败';
    }
  }





  /**** 导入Excel老师文件*/
  public function impTeacherExcel()
  {
    $faillog = ''; //导入失败的记录
    $user['groupid'] = cookie('jobid');
    $user['userclass'] = 1;

    $group = Db::table('shixi_grade')->where('id', $user['groupid'])->find();
    $data['province'] = $group['province'];
    $data['city'] = $group['city'];
    $data['user_school'] = $group['school'];
    $data['user_xi'] = $group['depart'];



    if (!empty($_FILES)) {
      try {
        $file = request()->file('file');
        validate(['file' => [
          //限制文件大小
          'fileSize'      =>  2 * 1024 * 1024,
          'fileExt'       =>  "xls,xlsx"
        ]], [
          'file.fileSize' =>  '上传的文件大小不能超过2M',
          'file.fileExt'  =>  '请上传后缀为xls,xlsx的文件'
        ])->check(['file' => $file]);
      } catch (\think\exception\ValidateException $e) {
        return "导入失败，请检查文件类型是否xls,xlsx,大小是否超过2Mb";
      }

      $info = \think\facade\Filesystem::disk('public')->putFile('shixi', $file);
      require '../extend/PHPExcel/PHPExcel.php';

      $objReader = \PHPExcel_IOFactory::createReader('Excel5');
      $Excel_name = "storage/" . $info;

      $aaa = is_readable($Excel_name);
      $extension = strtolower(pathinfo($Excel_name, PATHINFO_EXTENSION));


      if ($extension == 'xlsx') {
        $objReader = new \PHPExcel_Reader_Excel2007();
        $objPHPExcel = $objReader->load($Excel_name);
      } else if ($extension == 'xls') {
        $objReader = new \PHPExcel_Reader_Excel5();
        $objPHPExcel = $objReader->load($Excel_name);
      } else if ($extension == 'csv') {
        $PHPReader = new \PHPExcel_Reader_CSV();
        //默认输入字符集
        $PHPReader->setInputEncoding('GBK');
        //默认的分隔符
        $PHPReader->setDelimiter(',');
        //载入文件
        $objPHPExcel = $PHPReader->load($Excel_name);
      }
      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow(); // 取得总行数 
      $highestColumn = $sheet->getHighestColumn(); // 取得总列数 
      for ($i = 2; $i <= $highestRow; $i++) {
        $data['username'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue());
        $data['password'] = md5(trim($objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue()));
        $data['truename'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue());
        $data['mobile'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue());
        $user['student'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $i)->getValue());
        $data['user_class'] = 1;
        $data['regclass'] = 1;

        //判断手机号码是否正确

        //用户是否已注册过
        $exist = Db::table('user_base')->where('username', $data['username'])->where('user_school', $data['user_school'])->value('uid');
        if ($exist > 0) {
          //直接加入指导群中 
          $user['uid'] = $exist;
          //是否在群内已存在
          $existed = Db::table('shixi_inusers')->where('groupid', $user['groupid'])->where('uid', $user['uid'])->count();
          if ($existed == 0) {
            $res = Db::table('shixi_inusers')->insert($user);
          }
        } else {
          //注册再加入群
          $userId = Db::name('user_base')->insertGetId($data);
          if ($userId > 0) {
            $user['uid'] = $userId;

            $res = Db::table('shixi_inusers')->insert($user);
          } else {
            $faillog .= $data['truename'] . $data['username'] . '/';
          }
        }
      }



      View::assign('faillog', $faillog);
      return View::fetch('shixi/importresult');
    } else {
      View::error("请选择上传的文件");
    }
  }


  //管理员：导出教师
  public function exportTeacherData()
  {
    $columns = ['#ID', '工号', '姓名', '手机', '最多指导学生数'];
    $user['groupid'] = cookie('jobid');
    $query = Db::table('shixi_inusers')
      ->alias('a')
      ->join('user_base w', 'a.uid = w.uid')
      ->field('a.id,w.username,w.truename,w.mobile,a.student')
      ->where('a.groupid', $user['groupid'])
      ->where("a.userclass", 1)
      ->order("a.role desc")
      ->select()->toArray();
    $filename = "指导教师-" . date('Y-m-d', time()) . ".csv";
    csv_export($query, $columns, $filename);
  }



  //管理员：规范性文件包上传
  public function gfupload()
  {

    $xi = cookie('xi');
    $file = request()->file('file');
    $info = \think\facade\Filesystem::disk('public')->putFile('shixi', $file);

    if ($info) {
      $haved = Db::table('shixi_cailiaoclass')->where('xi', $xi)->where('flag', 1)->value('id'); //是否存在
      if ($haved) {
        // 成功上传后 获取上传信息
        $old = Db::table('shixi_cailiaoclass')->where('id', $haved)->value('example');
        $res = Db::table('shixi_cailiaoclass')->where('id', $haved)->update(['example' => $info]);
        if ($res) {
          //删除旧 
          if (file_exists("./uploads/" . $old)) {
            unlink("./uploads/" . $old);
          }

          return "上传成功";
        } else {
          return "上传失败";
        }
      } else {
        $data['title'] = "实习规范原始文件";
        $data['content'] = "学生按这个文件格式来整理实习文档";
        $data['uid'] = session('uid');
        $data['example'] = $info;
        $data['flag'] = 1;
        $data['xi'] = $xi;
        $res = Db::table('shixi_cailiaoclass')->insert($data);
        if ($res) {
          return "上传成功";
        } else {
          return "上传失败";
        }
      }
    } else {
      return "上传失败";
    }
  }



  //模拟登录
  public function login()
  {
    return $this->fetch();
  }


  //登录验证
  public function logined()
  {
    $user = input('get.user');
    $password = input('get.password');
    // 0管理员 1二级学院  2教务处 3老师 4学生
    if ($user == "1" && $password == "123456") {
      cookie('userClass', 1);
      session('userclass', 1);
      session('uid', $user);
      session('truename', $user);
      $this->success('登录成功', 'index/score/index');
    } else if ($user == "2" && $password == "123456") {
      cookie('userClass', 2);
      session('userclass', 2);
      session('uid', $user);
      session('truename', $user);
      $this->success('登录成功', 'index/score/index');
    } else if ($user == "3" && $password == "123456") {
      cookie('userClass', 3);
      session('userclass', 3);
      session('uid', $user);
      session('truename', $user);
      $this->success('登录成功', 'index/score/index');
    } else if ($user == "4" && $password == "123456") {
      cookie('userClass', 4);
      session('userclass', 4);
      session('uid', $user);
      session('truename', $user);
      $this->success('登录成功', 'index/score/index');
    } else if ($user == "0" && $password == "123456") {
      cookie('userClass', 10);
      session('userclass', 10);
      session('uid', $user);
      session('truename', $user);
      $this->success('登录成功', 'index/score/index');
    } else {
      $this->error('登录失败');
    }
  }


  //模拟退出登录
  public function logout()
  {
    session(null);
    cookie('userClass', null);

  }


  //后台代码
  public function admin()
  {
    //	       
    return $this->fetch();
  }
}
